import org.codehaus.groovy.grails.commons.GrailsClassUtils as GCU

grailsHome = Ant.project.properties."environment.GRAILS_HOME"

includeTargets << new File ( "${grailsHome}/scripts/Init.groovy" )
includeTargets << new File ( "${grailsHome}/scripts/TestApp.groovy" )
includeTargets << new File ( "${grailsHome}/scripts/Clean.groovy" )

target('default': "The description of the script goes here!") {

	depends(classpath, checkVersion, configureProxy)

	clean()
    loadEvents()
    testApp()

}

target(loadEvents: "Load Events from DbUnitEvents file") {
    try {

	    loadEventScript(file('DbUnitEvents'))

	    println "Events for dbunit registered successfully"

	} catch(Exception ex) {
		println "Could not load events, $ex"
	}
}

def file(name) {
    def result = null
    new File('.').eachFileRecurse { f ->
        if(f =~ "${name}") {
            result = f
        }
    }

    println "Registering events from $result"

    return result
}

void loadEventScript(theFile) {
    try {
        // Load up the given events script.
        def script = eventsClassLoader.parseClass(theFile).newInstance()

        // Pass the global binding to the script.
        script.binding = getBinding()

        // Execute the script.
        script.run()

        // The binding should now contain the event hooks provided by
        // script, so we remove them and add them to the 'eventHooks'
        // map.
        def entriesToRemove = []
        script.binding.variables.each {key, value ->
            // Check whether this binding variable is an event hook.
            def m = key =~ /event([A-Z]\w*)/
            if (m.matches()) {
                // It is, so add the hook to the global map of event
                // hooks.
                def eventName = m[0][1]
                def hooks = globalEventHooks[eventName]
                if (hooks == null) {
                    hooks = []
                    globalEventHooks[eventName] = hooks
                }

                hooks << value

                // This entry should now be removed from the global
                // binding.
                entriesToRemove << key
            }
        }

        // Remove the event hooks from the global binding.
        entriesToRemove.each { script.binding.variables.remove(it) }
    } catch (Throwable t) {
        println "Unable to load event script $theFile: ${t.message}"
        t.printStackTrace()
    }
}